/**
 * API服务模块
 * 统一管理网络请求，提供请求拦截和响应处理
 */

const { logger } = require('./logger')
const { API } = require('../config/index')

/**
 * 基础请求函数
 * @param {Object} options - 请求选项
 * @returns {Promise} 请求Promise
 */
function request(options) {
  const { url, method = 'GET', data = {}, header = {}, ...rest } = options

  // 构建完整URL
  const fullUrl = /^https?:\/\//.test(url) ? url : `${API.BASE_URL}${url}`

  // 合并默认请求头
  const headers = {
    'content-type': 'application/json',
    ...header,
  }

  // 记录请求日志
  logger.debug('API请求', { url: fullUrl, method, data })

  return new Promise((resolve, reject) => {
    wx.request({
      url: fullUrl,
      method,
      data,
      header: headers,
      timeout: API.TIMEOUT,
      ...rest,
      success: res => {
        // 记录响应日志
        logger.debug('API响应', { url: fullUrl, statusCode: res.statusCode, data: res.data })

        // 处理HTTP状态码
        if (res.statusCode >= 200 && res.statusCode < 300) {
          resolve(res.data)
        } else {
          const error = new Error(`请求失败: ${res.statusCode}`)
          error.response = res
          reject(error)
        }
      },
      fail: err => {
        // 记录错误日志
        logger.error('API请求失败', { url: fullUrl, error: err })
        reject(err)
      },
    })
  })
}

/**
 * 带重试功能的请求函数
 * @param {Object} options - 请求选项
 * @param {number} retryCount - 重试次数
 * @param {number} retryDelay - 重试延迟(ms)
 * @returns {Promise} 请求Promise
 */
function requestWithRetry(options, retryCount = API.RETRY_COUNT, retryDelay = 1000) {
  return new Promise((resolve, reject) => {
    const attempt = attemptCount => {
      request(options)
        .then(resolve)
        .catch(error => {
          // 判断是否需要重试
          if (attemptCount < retryCount) {
            logger.warn(`请求失败，${retryDelay}ms后重试(${attemptCount + 1}/${retryCount})`, {
              url: options.url,
            })
            setTimeout(() => attempt(attemptCount + 1), retryDelay)
          } else {
            reject(error)
          }
        })
    }

    attempt(0)
  })
}

// 导出API方法
module.exports = {
  // 基础请求方法
  request,
  requestWithRetry,

  // HTTP方法别名
  get: (url, params = {}, options = {}) => {
    return request({
      url,
      method: 'GET',
      data: params,
      ...options,
    })
  },

  post: (url, data = {}, options = {}) => {
    return request({
      url,
      method: 'POST',
      data,
      ...options,
    })
  },

  put: (url, data = {}, options = {}) => {
    return request({
      url,
      method: 'PUT',
      data,
      ...options,
    })
  },

  delete: (url, data = {}, options = {}) => {
    return request({
      url,
      method: 'DELETE',
      data,
      ...options,
    })
  },
}
